<script setup>
import {useUserStore} from "@/stores";
import {onBeforeMount, ref,computed} from "vue";
import axios from "axios";
import ProductCard from "@/components/ProductCard.vue";

const userStore=useUserStore()
const GoodsNumber = ref([] )//推荐商品的id集合

//获取推荐商品请求
const fetchRecommendedItems = async () => {
  try {
    // 将id作为查询参数传递给请求
    const res = await axios.get(`http://127.0.0.1:8080/RecommendedByItem?id=${userStore.userid}`)
    GoodsNumber.value = res.data // 假设返回的数据是数组格式
    fetchGoodsList(GoodsNumber.value)
    // console.log(GoodsNumber.value)
  } catch (error) {
    console.error('请求失败:', error);
  }
}

const productList = ref([]);
//发起请求获取商品列表
const fetchGoodsList = async (ids) => {
  // 假设这是你要发送的商品ID数组
  // const ids = [1, 2, 3, 4, 5]
  // 发送POST请求到后端接口
  const response = await axios.post('http://localhost:8081/goods/ArrayList', ids);
  productList.value = response.data.data; // 假设返回的商品列表在data字段
  console.log(productList.value)
  ElMessage.success("推荐商品获取成功"); // 显示成功消息

}

// 只渲染productList数组中的前八个数据
const firstEightProducts = computed(() => productList.value.slice(0, 8));

onBeforeMount(async =>{
  fetchRecommendedItems()
})

</script>

<template>
  <div>
    <h1>猜你喜欢</h1>
    <div class="elSlideShow">
      <product-card
          class="product-card"
          v-for="(product) in firstEightProducts "
          :key="product.id"
          :product-image="product.img"
          :product-name="product.name"
          :product-description="product.info"
          :product-price="product.price"
      >
      </product-card>
    </div>
  </div>

</template>

<style scoped>
h1 {
  text-align: center;
  font-family: Montserrat, sans-serif;
  color: #333;
}
.elSlideShow{
  height: 50rem;
  width: 90%;
  margin-left: 5%;
  margin-top: 2rem;
  display: flex;
  flex-wrap: wrap; /* 允许盒子换行 */
}

.product-card {
//flex-basis: calc(25% - 10px); /* 每个盒子占据的空间，减去间隔 */
  /* 盒子之间的间隔 */
  margin: 10px 10px 10px 40px;
}
</style>
